package com.atguigu.gmall.common.interceptor;

import com.atguigu.gmall.common.util.AuthContextHolder;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author gsy
 * @date 2021年09月08日19:47
 * Description
 */
public class FeignInterceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate requestTemplate) {
        //当前请求 任何地方都能获得当前请求
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (requestAttributes!=null){
            HttpServletRequest request = requestAttributes.getRequest();
            if (request!=null){
                String userId = AuthContextHolder.getUserId(request);
                String userTempId = AuthContextHolder.getUserTempId(request);
                //requestTemplate 远程调用发生的请求
                if (!StringUtils.isEmpty(userId)){
                    requestTemplate.header("userId",userId);
                }
                if (!StringUtils.isEmpty(userTempId)){
                    requestTemplate.header("userTempId",userTempId);
                }
            }



        }

    }
}
